package cn.zust.edu.cn;

public class Triangle implements IShape {
	private Point ptA, ptB, ptC;
	private final double edgeA, edgeB, edgeC;

	public Triangle(Point a, Point b, Point c) {
		ptA = a;
		ptB = b;
		ptC = c;
		edgeA = distance(b, c);
		edgeB = distance(a, c);
		edgeC = distance(a, b);
	}

	private double distance(Point p1, Point p2) {
		int dx = p1.getX() - p2.getX();
		int dy = p1.getY() - p2.getY();
		return Math.sqrt(dx*dx + dy*dy);
	}

	@Override
	public double perimeter() {
		return edgeA + edgeB + edgeC;
	}

	@Override
	public double area() {
		double s = perimeter() / 2;
		return Math.sqrt(s * (s-edgeA) * (s-edgeB) * (s-edgeC));
	}

	@Override
	public void draw() {
		int minX = Math.min(Math.min(ptA.getX(), ptB.getX()), ptC.getX());
		int maxX = Math.max(Math.max(ptA.getX(), ptB.getX()), ptC.getX());
		int minY = Math.min(Math.min(ptA.getY(), ptB.getY()), ptC.getY());
		int maxY = Math.max(Math.max(ptA.getY(), ptB.getY()), ptC.getY());

		for (int y = minY; y <= maxY; y++) {
			for (int x = minX; x <= maxX; x++) {
				if (isOnEdge(x, y)) System.out.print("*");
				else System.out.print(" ");
			}
			System.out.println();
		}
	}

	private boolean isOnEdge(int x, int y) {
		return isBetween(x, y, ptA, ptB) ||
				isBetween(x, y, ptB, ptC) ||
				isBetween(x, y, ptC, ptA);
	}

	private boolean isBetween(int x, int y, Point p1, Point p2) {
		int dx = p2.getX() - p1.getX();
		int dy = p2.getY() - p1.getY();
		if (dx == 0 && dy == 0) return x == p1.getX() && y == p1.getY();

		double t = dx != 0 ? (double)(x - p1.getX())/dx : (double)(y - p1.getY())/dy;
		if (t < 0 || t > 1) return false;
		return x == p1.getX() + (int)(dx*t) && y == p1.getY() + (int)(dy*t);
	}
}

